<template>
  <div>
    <el-page-header @back="goBack"></el-page-header>

    <div class="createPage" v-if="!successShow">
      <div class="left">
        <div class="title">编辑资料</div>
        <div class="desc">
          修改联系电话需核试验身份
          <br />
          修改角色请联系管理员
        </div>
        <div class="leftImg">
          <img src="@/assets/imgs/geren/info1.png" alt="" />
        </div>
      </div>
      <div class="right">
        <el-form
          label-width="80px"
          :model="info"
          :rules="rules"
          ref="infoForm"
          label-position="top"
        >
          <el-form-item style="margin-top: 34px" label="头像">
            <el-upload
              :show-file-list="false"
              action="/merchantApi/oss/upload"
              :headers="{
                auth_token: getToken(),
                auth_tmp: curTmp,
                auth_tck: curTck,
              }"
              :on-success="handleSuccess"
            >
              <div class="uploadImg" v-if="info.headUrl">
                <img :src="imageUrl" alt="" />
              </div>
              <div class="uploadImg" v-else>
                <img :src="require('@/assets/imgs/geren/info3.png')" alt="" />
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="姓名"
            prop="realName"
            style="width: 52%"
            class="errorText"
          >
            <el-input
              v-model="info.realName"
              placeholder="姓名"
              clearable
              maxlength="50"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="联系电话"
            prop="mobile"
            style="width: 52%"
            class="errorText"
          >
            <el-input
              v-model="info.mobile"
              placeholder="联系电话"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="角色"
            style="width: 52%"
            class="errorText is-required"
          >
            <el-input
              v-model="info.roleName"
              placeholder="暂无角色"
              disabled
            ></el-input>
          </el-form-item>

          <el-form-item style="margin-top: 60px">
            <el-button class="width120" @click="goBack">取消</el-button>
            <el-button
              class="width120"
              type="primary"
              @click="submitForm('infoForm')"
              >提交</el-button
            >
          </el-form-item>
          <!-- <div class="text" style="position: absolute; top: 357px">
            修改联系电话需进行注册邮箱验证，你的注册邮箱会收到一条验证码，验证成功方可修改
          </div> -->
          <div class="text" style="position: absolute; top: 450px">
            当前不可变更角色，如有需要请联系贵司管理员
          </div>
        </el-form>
      </div>
      <el-dialog
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :show-close="false"
        title=""
        class="tkDialog"
        :visible.sync="phoneDialog"
        width="449px"
      >
        <div class="dialogTitle">联系电话验证</div>
        <el-form
          :model="phoneForm"
          :rules="rules1"
          ref="phoneForm"
          label-position="top"
          label-width="80px"
        >
          <el-form-item label="联系电话" prop="phone">
            <el-input
              placeholder="请输入新联系电话"
              v-model="phoneForm.phone"
              style="width: 225px"
              disabled
            ></el-input>
            <el-button
              style="width: 133px; margin-left: 10px"
              @click="getCodePhone"
              >{{ codeText }}</el-button
            >
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input
              placeholder="请输入新联系电话的验证码"
              v-model="phoneForm.code"
              style="width: 368px"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="phoneDialog = false" style="width: 120px"
            >取 消</el-button
          >
          <el-button
            type="primary"
            @click="phoneCodeFn('phoneForm')"
            style="width: 120px"
            >确 定</el-button
          >
        </span>
      </el-dialog>
      <codeEmailDialogVue
        type="EMAIL_BUSINESS_UPDATE_PHONE"
        :codeEmailDialog.sync="codeEmailDialog"
        @codeEmailState="codeEmailStateFn"
      />
    </div>
    <div class="success" v-if="successShow">
      <img src="@/assets/imgs/geren/check-circle.png" alt="" />
      <div>修改成功</div>
    </div>
  </div>
</template>

<script>
import { isMobile } from "@/utils/validate";
import { getToken, getUserInfo } from "@/utils/public";
import codeEmailDialogVue from "@/components/codeEmailDialog.vue";
import { mapMutations } from "vuex";
import crypto from "@/crypto";
import { randomWord } from "@/utils/getRandom";

export default {
  name: "gerenUserInfoEdit",
  components: {
    codeEmailDialogVue,
  },
  data() {
    return {
      curTmp: null,
      curTck: null,
      len: [8, 9, 10, 11, 12][
        Math.floor(Math.random() * [8, 9, 10, 11, 12].length)
      ],
      codeText: "获取短信验证码",
      phoneForm: { code: "", phone: "" },
      phoneDialog: false,
      successShow: false,
      rules: {
        headUrl: [{ required: true, message: "请上传头像", trigger: "change" }],
        realName: [
          { required: true, message: "请输入姓名", trigger: "change" },
          {
            pattern: /^(?!\s+).*(?<!\s)$/,
            message: "格式有误",
            trigger: "change",
          },
        ],
        mobile: [
          { required: true, message: "请输入联系电话", trigger: "change" },
          { validator: this.checkPhone, trigger: "change" },
        ],
      },
      rules1: {
        code: [
          { required: true, message: "验证码不能为空", trigger: "change" },
          {
            min: 6,
            max: 6,
            message: "请输入正确的6位数验证码",
            trigger: "change",
          },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "change" },
          { validator: this.checkPhone, trigger: "change" },
        ],
      },
      codeEmailDialog: false,
      imageUrl: "",
      info: { headUrl: "", realName: "", mobile: "", roleName: "" },
      initial: {},
    };
  },
  created() {
    this.curTmp = new Date().getTime();
    this.curTck = crypto.set(
      getToken() + "_" + this.curTmp + "_" + randomWord(this.len),
      "a1g0qoalvv19aed3"
    );

    this.getList();
  },
  mounted() {},
  methods: {
    ...mapMutations(["changeLive"]),
    getToken,
    getUserInfo,
    phoneCodeFn(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.phoneEditFn();
        } else {
          return false;
        }
      });
    },
    getCodePhone() {
      if (this.codeText == "获取短信验证码") {
        if (isMobile(this.phoneForm.phone)) {
          // var params = new FormData();
          // params.append("phone", this.phoneForm.phone);
          // params.append("verificationCodeEnum", "SMS_BUSINESS_CHECK_PHONE");
          let params = {
            verificationCodeEnum: "SMS_BUSINESS_CHECK_PHONE",
            phone: this.phoneForm.phone
          };
          this.$http.post(`/sms/sendVerificationCode`, params).then((res) => {
            if (res.code === "0000") {
              var time = 60;
              this.codeText = time + "s 重新发送";
              var setTime = setInterval(() => {
                time = time - 1;
                this.codeText = time + "s 重新发送";
                if (time == 0) {
                  clearInterval(setTime);
                  this.codeText = "获取短信验证码";
                }
              }, 1000);
            }
          });
        } else {
          this.$message.closeAll();
          this.$message.warning("请输入有效的联系电话");
        }
      }
    },
    checkPhone(rule, value, callback) {
      if (isMobile(value)) {
        callback();
      } else {
        callback(new Error("请输入有效的联系电话"));
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.initial.mobile != this.info.mobile) {
            this.$http
              .get(`/sys/user/verificationPhoneExist?phone=${this.info.mobile}`)
              .then((res) => {
                if (res.code === "0000") {
                  // this.codeEmailDialog = true;
                  this.phoneDialog = true;
                  this.phoneForm.phone = this.info.mobile;
                }
              });
          } else {
            this.phoneEditFn();
          }
        } else {
          return false;
        }
      });
    },
    goBack() {
      this.$backTo(`/geren/userInfo`);
    },
    codeEmailStateFn(val) {
      if (val) {
        (this.phoneDialog = true);
        this.phoneForm.phone = this.info.mobile;
      }
    },
    handleSuccess(res, file) {
      this.info.headUrl = res.data.id;
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    getList() {
      this.$http.get("/sys/user/getUser").then((res) => {
        if (res.code === "0000") {
          this.initial = res.data;
          this.info = JSON.parse(JSON.stringify(res.data));
          setTimeout(() => {
            this.$refs["infoForm"].clearValidate();
          }, 0);
          if (this.info.headUrl) {
            this.imageUrl =
              window.location.origin +
              `/merchantApi/oss/view?id=${this.info.headUrl}`;
          }
        }
      });
    },
    phoneEditFn() {
      var operationTypeList = {
        id: this.info.id,
        headUrl: this.info.headUrl,
        realName: this.info.realName,
        verificationCode: this.phoneForm.code,
        // operationType:'updatePhone',
        mobile: this.info.mobile,
      };
      this.$http
        .post("/sys/user/updateUserBaseInfo", operationTypeList)
        .then((res) => {
          if (res.code === "0000") {
            this.phoneDialog = false;
            this.successShow = true;
            setTimeout(() => {
              this.testCancel();
            }, 1500);
          }
        });
    },
    testCancel() {
      this.$backTo("/geren/userInfo");
    },
  },
};
</script>

<style lang="scss" scoped>
.createPage {
  background: #fff;
  color: #666;
  margin-top: 20px;
  height: 84vh;
  .left {
    float: left;
    width: 50%;
    padding: 74px 13%;

    .title {
      width: 96px;
      height: 33px;
      font-size: 24px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #1d1c1c;
      line-height: 33px;
    }
    .desc {
      margin-top: 18px;
      width: 168px;
      height: 48px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
      line-height: 24px;
    }
    .leftImg {
      margin-top: 71px;
      width: 22.1vw;
      height: 15.4vw;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
  .right {
    position: relative;
    margin-top: 120px;
    float: right;
    width: 50%;
    .errorText {
      :deep(.el-form-item__error) {
        width: 120px;
        position: absolute;
        left: 102%;
        top: 8px;
      }
    }

    .uploadImg {
      width: 80px;
      height: 80px;
      border-radius: 10px;
      overflow: hidden;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .title {
      color: #4f595f;
      position: relative;
      font-size: 24px;
      font-weight: 600;
      &::before {
        content: "";
        width: 4px;
        height: 24px;
        background: #03bfc6;
        position: absolute;
        left: -34px;
        top: 7px;
      }
    }
    .wrap {
      width: 400px;
      display: flex;
      justify-content: space-between;
    }
    .text {
      height: 17px;
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #869daa;
      line-height: 17px;
    }
  }
}
.success {
  background: #fff;
  margin-top: 20px;
  height: 84vh;
  text-align: center;
  padding-top: 129px;
  div {
    margin-top: 10px;
    height: 32px;
    font-size: 24px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #1f1d1d;
    line-height: 32px;
  }
}
</style>
